import { Component, OnInit, Injector } from '@angular/core';
import { DrillContentComponent } from '../drill-content/drill-content.component';
import { SignalRService } from '../../../core/service/singnalr-service';
import { NzModalService } from 'ng-zorro-antd';
import { map } from 'rxjs/operators';
import { Observable, Observer } from 'rxjs/';
import { DomSanitizer } from '@angular/platform-browser';

@Component({
  selector: 'app-drill-drag-content',
  templateUrl: './drill-drag-content.component.html',
  styleUrls: ['./drill-drag-content.component.scss']
})
export class DrillDragContentComponent extends DrillContentComponent implements OnInit {


  reslutList = new DragContent([], []);

  dragItem;
  dragStart(ev, item) {
    this.dragItem = item;
  }

  drop(ev, item) {
    ev.preventDefault();
    if (item && !item.dragFlowForms) {
      item.dragFlowForms = [];
    }
    if (item && this.dragItem) {
      item.dragFlowForms.push(this.dragItem);
      this.reslutList.forms = this.reslutList.forms.filter(e => e.id !== this.dragItem.id);
      this.dragItem = null;

    }
  }

  allowDrop(ev) {
    ev.preventDefault();
  }

  constructor(
    injector: Injector,
    sanitizer: DomSanitizer,
    public signalrService: SignalRService,

    public madol: NzModalService
  ) {
    super(injector, signalrService, sanitizer, madol);
  }

  ngOnInit() {
    this.route.queryParamMap
      .pipe(map(params => params.get('id') || null))
      .subscribe(e => {
        this.recordId = Number(e);
        if (!this.recordId) {
          this.message.error('无法确定主键信息!');
        } else {
          this.GetDataObserver.subscribe(sb => {
            this.currentIndex = this.flowRecordOutput['currentStep'];
          });
        }
      });
  }

  /**
   * 用于初始化，显示其他步骤数据内容的初始化。
   */
  iniObserable() {
    const this1 = this;
    this.GetDataObserver = Observable.create(async function (observer: Observer<any>) {
      const url = `drillrecord/GetDragContent/?recordId=${this1.recordId}`;
      // 获取表单数据
      const res = await this1.httpService.get<any>(url);
      this1.flowRecordOutput = res;
      // 如果有演练记录，转换演练记录。
      if (res.dataJson) {
        this1.reslutList = JSON.parse(res.dataJson);
      } else {
        // 根据表单内容初始化。
        this1.reslutList = new DragContent([...res.dragDrillFlows], [...res.dragFlowForms]);
      }
    });
  }

  /**
   * 双击删除流程中的节点
   * @param pitem 父节点ID
   * @param item 操作内容
   */
  delElement(pitem, item) {
    if (this.flowRecordOutput.drillStatus !== 2) {
      this.reslutList.flows.forEach(e => {
        if (e.id === pitem) {
          e.dragFlowForms = e.dragFlowForms.filter(e1 => e1.id !== item.id);
        }
      });
      this.reslutList.forms.push(item);
    }
  }

  /**
   * 保存操作内容
   */
  saveResult() {
    if (this.reslutList.forms && this.reslutList.forms.length > 0) {
      this.message.error('仍有未分配完的流程信息！');
      return;
    }
    this.nzModalService.confirm({
      nzTitle: '提示',
      nzContent: '是否要提交操作内容。',
      nzOnOk: async () => {
        let hasWrong = false;
        this.reslutList.flows.forEach(e => {
          const wrongs = e.dragFlowForms.filter(e1 => e1.flowId !== e.id);
          if (wrongs && wrongs.length > 0) {
            hasWrong = true;
            return;
          }
        });
        const jsonData = JSON.stringify(this.reslutList);
        const postBody = {
          recordId: this.flowRecordOutput.recordId,
          dataJson: jsonData,
          hasError: hasWrong,
        };
        await this.httpService.post<any>('drillrecord/AddDragOperation', postBody);
        this.GetDataObserver.subscribe();
      }
    });

  }

  /**
   * 获取错误提示信息。
   * @param nowPid 流程ID
   * @param item 判断内容
   */
  getErrorTitle(nowPid, item) {
    if (this.flowRecordOutput.drillStatus === 2) {
      if (nowPid === item.flowId) {
        return "放置正确";
      } else {
        const findFlow = this.reslutList.flows.filter(e => e.id === item.flowId);
        if (findFlow && findFlow.length > 0) {
          return `本内容应该放置在【${findFlow[0].flowName}】`;
        }
        return "无法确定位置";
      }
    } else {
      return "";
    }

  }

  /**
   * 判断是否有错误。
   * @param nowPid 流程ID
   * @param item 判断内容
   */
  isError(nowPid, item) {
    if (this.flowRecordOutput.drillStatus === 2) {
      return nowPid === item.flowId;
    } else {
      return true;
    }
  }
}

export class DragContent {
  constructor(
    public flows = [],
    public forms = []
  ) { }
}